'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { useParameterPermissions } from '@/hooks/use-parameter-permissions'
import { useAuth } from '@/hooks/use-auth'
import { ArrowLeft } from 'lucide-react'

export default function TestSpecialtyDisplayPage() {
  const [selectedSpecialty, setSelectedSpecialty] = useState('procurement')
  const { user, loading: authLoading } = useAuth()
  const router = useRouter()

  const {
    fields,
    loading,
    error,
    user: paramUser,
    permissions
  } = useParameterPermissions('table_c2', 1)

  const getDataSourceColor = (source: string) => {
    const colors: Record<string, string> = {
      'P': 'bg-blue-100 text-blue-800',
      'E': 'bg-green-100 text-green-800',
      'M': 'bg-orange-100 text-orange-800',
      'O': 'bg-purple-100 text-purple-800',
      'C': 'bg-yellow-100 text-yellow-800',
      'R': 'bg-red-100 text-red-800'
    }
    return colors[source] || 'bg-gray-100 text-gray-800'
  }

  const getSpecialtyDataSources = (specialty: string): string[] => {
    const mapping: Record<string, string[]> = {
      'procurement': ['P'],
      'design': ['E'],
      'monitoring': ['M'],
      'construction': ['C'],
      'operations': ['O', 'R'],
      'all': ['P', 'E', 'M', 'O', 'C', 'R']
    }
    return mapping[specialty] || []
  }

  const getSpecialtyName = (specialty: string) => {
    const names: Record<string, string> = {
      'procurement': '采购',
      'design': '设计',
      'monitoring': '监测',
      'construction': '施工',
      'operations': '运维',
      'all': '全部'
    }
    return names[specialty] || specialty
  }

  if (authLoading || loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-2 text-gray-600">加载中...</p>
        </div>
      </div>
    )
  }

  if (!user) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <Card className="w-full max-w-md">
          <CardHeader>
            <CardTitle>需要登录</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-gray-600 mb-4">请先登录以查看专业字段测试</p>
            <Button onClick={() => router.push('/login')} className="w-full">
              前往登录
            </Button>
          </CardContent>
        </Card>
      </div>
    )
  }

  // 获取选中专业的数据来源
  const selectedDataSources = getSpecialtyDataSources(selectedSpecialty)
  
  // 过滤字段
  const filteredFields = fields.filter(field => 
    selectedDataSources.includes(field.data_source)
  )

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* 页面头部 */}
        <div className="mb-6">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <Button
                variant="outline"
                onClick={() => router.push('/')}
                className="flex items-center space-x-2"
              >
                <ArrowLeft className="h-4 w-4" />
                <span>返回首页</span>
              </Button>
              
              <div>
                <h1 className="text-2xl font-bold text-gray-900">
                  专业字段显示测试
                </h1>
                <p className="text-gray-600">测试不同专业的字段显示和数据来源</p>
              </div>
            </div>
          </div>
        </div>

        {/* 专业选择 */}
        <Card className="mb-6">
          <CardHeader>
            <CardTitle>选择专业</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center space-x-4">
              <label className="text-sm font-medium text-gray-600">专业:</label>
              <select
                value={selectedSpecialty}
                onChange={(e) => setSelectedSpecialty(e.target.value)}
                className="px-3 py-2 border rounded-md text-sm bg-white min-w-[120px]"
              >
                <option value="procurement">采购</option>
                <option value="design">设计</option>
                <option value="monitoring">监测</option>
                <option value="construction">施工</option>
                <option value="operations">运维</option>
                <option value="all">全部</option>
              </select>
              <div className="text-sm text-gray-500">
                当前显示: {getSpecialtyName(selectedSpecialty)} ({filteredFields.length} 个字段)
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 字段列表 */}
        <Card>
          <CardHeader>
            <CardTitle>{getSpecialtyName(selectedSpecialty)}专业字段列表</CardTitle>
          </CardHeader>
          <CardContent>
            {filteredFields.length > 0 ? (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>字段名称</TableHead>
                    <TableHead>描述</TableHead>
                    <TableHead>数据来源</TableHead>
                    <TableHead>数据类型</TableHead>
                    <TableHead>计量单位</TableHead>
                    <TableHead>是否必填</TableHead>
                    <TableHead>示例</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredFields.map((field) => (
                    <TableRow key={field.id}>
                      <TableCell className="font-medium">
                        {field.field_name}
                      </TableCell>
                      <TableCell className="text-sm text-gray-600">
                        {field.field_description}
                      </TableCell>
                      <TableCell>
                        <Badge className={getDataSourceColor(field.data_source)}>
                          {field.data_source}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <Badge variant="outline">{field.data_type}</Badge>
                      </TableCell>
                      <TableCell>{field.measurement_unit}</TableCell>
                      <TableCell>
                        {field.is_required ? (
                          <Badge variant="destructive" className="text-xs">必填</Badge>
                        ) : (
                          <Badge variant="secondary" className="text-xs">可选</Badge>
                        )}
                      </TableCell>
                      <TableCell className="text-sm text-gray-500">
                        {field.example_description}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            ) : (
              <div className="text-center py-8 text-gray-500">
                当前专业没有字段数据
              </div>
            )}
          </CardContent>
        </Card>

        {/* 数据来源统计 */}
        <Card className="mt-6">
          <CardHeader>
            <CardTitle>数据来源统计</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
              {['P', 'E', 'M', 'O', 'C', 'R'].map(source => {
                const sourceFields = fields.filter(f => f.data_source === source)
                const isSelected = selectedDataSources.includes(source)
                return (
                  <div key={source} className={`p-3 rounded-lg border ${isSelected ? 'border-blue-300 bg-blue-50' : 'border-gray-200'}`}>
                    <div className="text-center">
                      <Badge className={getDataSourceColor(source)}>
                        {source}
                      </Badge>
                      <div className="mt-2 text-lg font-semibold">{sourceFields.length}</div>
                      <div className="text-xs text-gray-500">个字段</div>
                    </div>
                  </div>
                )
              })}
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
